from sqlalchemy import select
from domain.models.models import ActivityComment, User
from domain.models.models import Activity
from db.db import async_session

async def get_comments(activity_id, page, page_size):
    """获取活动的所有评论
    Args:
        activity_id: 活动ID
        page: 页码
        page_size: 每页数量
    Returns:
        list: 评论列表
    """
    async with async_session() as session:
        # 查询评论及关联的用户信息
        result = await session.execute(
            select(ActivityComment, User).join(
                User, ActivityComment.user_id == User.id
            ).where(
                ActivityComment.activity_id == activity_id,
                ActivityComment.is_delete == 0
            ).order_by(ActivityComment.c_time.asc())  # 使用 c_time 字段进行排序
            .offset((page - 1) * page_size)
            .limit(page_size)
        )
        
        comments = []
        for comment, user in result:
            # 格式化评论数据
            comment_data = {
                'id': comment.id,
                'content': comment.content,
                'image': comment.image,
                'created_at': comment.c_time.strftime('%Y-%m-%d %H:%M:%S'),  # 使用 c_time
                'parent_id': comment.parent_id,
                'user': {
                    'id': user.id,
                    'name': user.name,
                    'photo_url': user.photo_url
                }
            }
            comments.append(comment_data)
            
        return comments

async def create_comment(comment_data):
    async with async_session() as session:
        try:
            # 如果有父评论ID，先获取父评论的用户ID
            parent_user_id = None
            if comment_data.get('parent_id', -1) > 0:
                parent_comment_result = await session.execute(
                    select(ActivityComment).where(
                        ActivityComment.id == comment_data['parent_id'],
                        ActivityComment.is_delete == 0
                    )
                )
                parent_comment = parent_comment_result.scalar_one_or_none()
                if parent_comment:
                    parent_user_id = parent_comment.user_id
                else:
                    return False, "父评论不存在"

            # 构建评论对象
            comment = ActivityComment(
                user_id=comment_data['user_id'],
                activity_id=comment_data['activity_id'],
                content=comment_data.get('content', ''),
                image=comment_data.get('image', ''),
                parent_id=comment_data.get('parent_id', -1)
            )
            
            # 添加到数据库
            session.add(comment)
            await session.commit()
            await session.refresh(comment)
            
            # 查询评论用户信息
            user_result = await session.execute(
                select(User).where(User.id == comment.user_id)
            )
            user = user_result.scalar_one()
            
            # 构建返回数据
            return True, {
                'id': comment.id,
                'content': comment.content,
                'image': comment.image,
                'created_at': comment.c_time.strftime('%Y-%m-%d %H:%M:%S'),
                'parent_id': comment.parent_id,
                'parent_user_id': parent_user_id,  # 添加父评论用户ID
                'user': {
                    'id': user.id,
                    'name': user.name,
                    'photo_url': user.photo_url
                }
            }
            
        except Exception as e:
            await session.rollback()
            print(f"创建评论失败: {str(e)}")
            return False, str(e)

async def delete_comment(comment_id, user_id):
    """删除评论
    Args:
        comment_id: 评论ID
        user_id: 用户ID（用于验证权限）
    Returns:
        tuple: (是否成功, 结果信息)
    """
    async with async_session() as session:
        try:
            # 查询评论及其关联的活动信息
            result = await session.execute(
                select(ActivityComment, Activity).join(
                    Activity, ActivityComment.activity_id == Activity.id
                ).where(
                    ActivityComment.id == comment_id,
                    ActivityComment.is_delete == 0
                )
            )
            comment_activity = result.first()
            
            # 评论不存在
            if not comment_activity:
                return False, "评论不存在"
            
            comment, activity = comment_activity
            
            # 验证用户权限：评论作者或活动发布者都可以删除评论
            if comment.user_id != user_id and activity.created_user_id != user_id:
                return False, "无权删除此评论"
            
            # 软删除评论
            comment.is_delete = 1
            await session.commit()
            
            return True, "删除成功"
            
        except Exception as e:
            await session.rollback()
            print(f"删除评论失败: {str(e)}")
            return False, str(e)